#!/usr/bin/env python
# -*- coding: utf8 -*-
# title       :
# description :
# author      :'ShenMeng'


import collections
import maya.mel as mel
import maya.cmds as cmds
import yaml
import os


class VerFbxExport(object):
    def __init__(self, filePath, config='fbx_config.yml'):
        """
        exporter = VerFbxExport(filePath="x:/xx/xx.abc", config='fbx_config.yml')
        exporter.exportObjects = nodesList
        exporter.main()
        """
        if not cmds.pluginInfo("fbxmaya.mll", q=1, l=1):
            cmds.loadPlugin( "fbxmaya.mll")
        self.exportObjects = None
        self.outPath = filePath
        self.validatePath(self.outPath)
        self._config = config
        
    @staticmethod
    def validatePath(filePath):
        if not os.path.isdir(os.path.dirname(filePath)):
            os.makedirs(os.path.dirname(filePath))
        
    def _initData(self):
        configFile = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'config', self._config)
        if not os.path.isfile(configFile):
            raise RuntimeError("config file not exists: %s \n" % configFile)
        data = self.getConfigData(configFile)
        optionsData = data.get('options', None)
        if not optionsData:
            raise RuntimeError("config error.")
        self._setOption(optionsData)
            
    @staticmethod
    def getConfigData(configFile):
        data = None
        with open(configFile) as f:
            data = yaml.load(f)
        if data:
            return data
        else:
            raise RuntimeError("load config data is none.")
            
    @staticmethod
    def _setOption(data):
        _temp = []
        for attr, value in data.iteritems():
            if isinstance(value, str):
                _temp.append('FBXProperty {attr} -v "{value}"'.format(attr=attr, value=value))
            elif isinstance(value, bool):
                _temp.append('FBXProperty {attr} -v {value}'.format(attr=attr, value="true" if value else "false"))
            else:
                _temp.append('FBXProperty {attr} -v {value}'.format(attr=attr, value=value))
        if _temp:
            mel.eval("""%s""" % ';'.join(_temp)) 
        else:
            raise RuntimeError("set fbx property failure.")
            
    def main(self, sl=1):
        self._initData()
        if not self.exportObjects:
            raise RuntimeError("Please set exportObjects.")
        cmds.select(cl=1)
        cmds.select(self.exportObjects)
        cmds.file(self.outPath, force=1, options="v=0;", typ="FBX export", pr=1, es=sl)
        return self.outPath